// Flutter imports:
import 'package:flutter/material.dart';
import 'package:flutter_picker_plus/flutter_picker_plus.dart';

// Package imports:
import 'package:get/get.dart';
import 'package:palmf_hid/common/services/Db.dart';
import 'package:palmf_hid/common/utils/database_backup_util/database_backup_util.dart';
import 'package:palmf_hid/common/utils/permission/permission_utils.dart';
import 'package:palmf_hid/common/utils/storage_manager.dart';
import 'package:palmf_hid/common/utils/utils.dart';
import 'package:palmf_hid/pages/main/main_logic.dart';
import 'package:pull_to_refresh/pull_to_refresh.dart';

// Project imports:
import 'show_history_data_state.dart';

class ShowHistoryDataLogic extends GetxController {
  final ShowHistoryDataState state = ShowHistoryDataState();
  final dataBackLogic = Get.put(MainLogic());
  String xlsNamePath =
      '${StorageManager.appDirectory.path}/${'detectionRecord'.tr}.xlsx';

  //列表页码
  int pageNum = 0;
  int pageSize = 10;
  int total = 0;

  final GlobalKey refresherKey = GlobalKey();
  final RefreshController refreshController =
      RefreshController(initialRefresh: true);
  final searchFocusNode = FocusNode();
  final TextEditingController textEditingController = TextEditingController();

  @override
  void onReady() {
    // TODO: implement onReady
    super.onReady();
  }

  @override
  void onClose() {
    // TODO: implement onClose
    super.onClose();
  }

  //加载更多
  void onLoading() {
    if (state.historyResultList.length < total) {
      getLibraryList().then((_) {
        refreshController.loadComplete();
      }).catchError((_) {
        refreshController.loadFailed();
      });
    } else {
      refreshController.loadNoData();
    }
  }

//刷新
  Future<void> onRefresh() async {
    MyLogUtil().i(total);
    getLibraryList(isRefresh: true).then((value) {
      refreshController.requestRefresh();
      refreshController.refreshCompleted(resetFooterState: true);
    }).catchError((e) {
      MyLogUtil().i(e);
      refreshController.refreshFailed();
    });
  }

  // 拉取数据
  Future<void> getLibraryList({bool isRefresh = false}) async {
    if (isRefresh == true) {
      pageNum = 0;
      state.historyResultList.clear();
      state.allChecked = false;
      state.selectCount = 0;
      MyLogUtil().i("清空了吗？  ${state.historyResultList.length}");
    } else {
      pageNum++;
    }

    var localData = await DbService.to.allResultDataByPage(
        pageSize, pageNum, state.searchContent, state.startTime, state.endTime);

    state.historyResultList.addAll(localData);
    total = await DbService.to.allResultDataCount;
    if (state.searchContent.isNotEmpty) {
      state.total = 0;
    } else {
      state.total = total;
    }
  }

  //备份数据
  Future<void> backupData() async {
    var value = await PermissionUtils.checkStoragePermission();
    if (value) {
      DatabaseBackupUtil.backDatabase();
    }
    // forwardingToPc(testData, qualifiedCharacteristic["B4:10:7B:C0:55:A8"]!);
  }

//恢复备份数据
  Future<bool> restoreData() async {
    var value = await PermissionUtils.checkStoragePermission();
    if (value) {
      bool value = await DatabaseBackupUtil.restoreDatabase();
      refreshController.requestRefresh();
      return value;
    } else {
      return false;
    }
  }

  Future<void> needRefresh() async {
    // await dataBackLogic.getHistoryList();
  }



  ///显示日期选择
  showDateSelect(int type) {
    var nowTime = DateTime.now();
    Picker picker = Picker(
        adapter: DateTimePickerAdapter(
            value: nowTime,
            type: PickerDateTimeType.kYMD,
            minValue: DateTime(nowTime.year - 1),
            maxValue: nowTime),
        changeToFirst: true,
        cancelText: 'cancel'.tr,
        confirmText: 'confirm'.tr,
        textAlign: TextAlign.center,
        columnPadding: const EdgeInsets.all(8.0),
        onConfirm: (Picker picker, List value) {
          DateTime? p = (picker.adapter as DateTimePickerAdapter).value;
          if (type == 0) {
            state.startTime =
                '${p?.year}-${timeFormatRepair(p?.month ?? 0)}-${timeFormatRepair(p?.day ?? 0)}';
          } else {
            state.endTime =
                '${p?.year}-${timeFormatRepair(p?.month ?? 0)}-${timeFormatRepair(p?.day ?? 0)}';
          }
        });

    picker.showModal(Get.context!);
  }

  String timeFormatRepair(int num) {
    String result = "$num";
    if (num < 10) {
      result = "0$num";
    }
    return result;
  }

  void handleSearch() {
    if (state.endTime != "" && state.startTime == "") {
      Get.snackbar("notice".tr, '${'please_select'.tr} ${"startTime".tr}');
      return;
    }

    refreshController.requestRefresh();
  }
}
